<template>
  <div class="market-sentiment-analysis bg-white dark:bg-gray-700 rounded-lg shadow p-4">
    <h2 class="text-lg font-semibold mb-4 dark:text-gray-200">市场情绪分析</h2>
    
    <div v-if="loading" class="flex justify-center items-center h-64">
      <LoadingSpinner />
    </div>
    
    <div v-else-if="error" class="text-center text-red-600 dark:text-red-400">
      {{ error }}
    </div>
    
    <div v-else>
      <!-- 情绪指标概览 -->
      <div class="grid grid-cols-3 gap-4 mb-6">
        <div class="p-3 bg-blue-50 dark:bg-blue-900 rounded-lg">
          <div class="text-sm text-blue-600 dark:text-blue-300">恐慌/贪婪指数</div>
          <div class="text-2xl font-bold" :class="getSentimentColor(sentimentData.fearGreedIndex)">
            {{ sentimentData.fearGreedIndex }}
          </div>
          <div class="text-xs text-gray-500 dark:text-gray-400">
            {{ getSentimentLabel(sentimentData.fearGreedIndex) }}
          </div>
        </div>
        
        <div class="p-3 bg-green-50 dark:bg-green-900 rounded-lg">
          <div class="text-sm text-green-600 dark:text-green-300">市场信心指数</div>
          <div class="text-2xl font-bold" :class="getConfidenceColor(sentimentData.marketConfidence)">
            {{ sentimentData.marketConfidence.toFixed(2) }}
          </div>
          <div class="text-xs text-gray-500 dark:text-gray-400">
            {{ getConfidenceLabel(sentimentData.marketConfidence) }}
          </div>
        </div>
        
        <div class="p-3 bg-purple-50 dark:bg-purple-900 rounded-lg">
          <div class="text-sm text-purple-600 dark:text-purple-300">社交媒体情绪</div>
          <div class="text-2xl font-bold" :class="getSentimentColor(sentimentData.socialMediaSentiment)">
            {{ sentimentData.socialMediaSentiment.toFixed(2) }}
          </div>
          <div class="text-xs text-gray-500 dark:text-gray-400">
            {{ getSentimentLabel(sentimentData.socialMediaSentiment) }}
          </div>
        </div>
      </div>
      
      <!-- 情绪趋势图 -->
      <div class="mb-6">
        <h3 class="text-md font-medium mb-2 dark:text-gray-200">情绪趋势</h3>
        <div class="h-64">
          <canvas ref="sentimentTrendChart"></canvas>
        </div>
      </div>
      
      <!-- 热门话题和关键词 -->
      <div class="mb-6">
        <h3 class="text-md font-medium mb-2 dark:text-gray-200">热门话题和关键词</h3>
        <div class="flex flex-wrap gap-2">
          <span 
            v-for="(topic, index) in sentimentData.hotTopics" 
            :key="index"
            class="px-2 py-1 bg-gray-200 dark:bg-gray-600 rounded-full text-sm"
            :class="getTopicColor(topic.sentiment)"
          >
            {{ topic.name }}
          </span>
        </div>
      </div>
      
      <!-- 新闻情绪分析 -->
      <div>
        <h3 class="text-md font-medium mb-2 dark:text-gray-200">新闻情绪分析</h3>
        <ul class="space-y-2">
          <li 
            v-for="(news, index) in sentimentData.newsAnalysis" 
            :key="index"
            class="flex items-center justify-between p-2 bg-gray-50 dark:bg-gray-800 rounded"
          >
            <span class="text-sm truncate mr-2">{{ news.title }}</span>
            <span 
              class="text-xs px-2 py-1 rounded-full"
              :class="getNewsSentimentClass(news.sentiment)"
            >
              {{ getNewsSentimentLabel(news.sentiment) }}
            </span>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { Chart } from 'chart.js/auto'
import { useAITradeStore } from '../store'
import errorHandler, { ErrorType, ErrorSeverity } from '../utils/error-handler'
import LoadingSpinner from './global/LoadingSpinner.vue'

const store = useAITradeStore()
const loading = ref(true)
const error = ref(null)
const sentimentData = ref(null)
const sentimentTrendChart = ref(null)
const chartInstance = ref(null)

// 获取市场情绪数据
async function fetchMarketSentiment() {
  try {
    loading.value = true
    error.value = null
    sentimentData.value = await store.getMarketSentiment()
  } catch (err) {
    error.value = '获取市场情绪数据失败'
    errorHandler.handleError(err, ErrorType.API, ErrorSeverity.WARNING)
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(async () => {
  await fetchMarketSentiment()
  if (sentimentData.value) {
    updateSentimentTrendChart()
  }
})

// 更新情绪趋势图表
function updateSentimentTrendChart() {
  if (!sentimentData.value || !sentimentTrendChart.value) return
  
  const ctx = sentimentTrendChart.value.getContext('2d')
  
  // 销毁旧的图表实例
  if (chartInstance.value) {
    chartInstance.value.destroy()
  }
  
  // 创建新的图表
  chartInstance.value = new Chart(ctx, {
    type: 'line',
    data: {
      labels: sentimentData.value.trendDates,
      datasets: [
        {
          label: '恐慌/贪婪指数',
          data: sentimentData.value.fearGreedTrend,
          borderColor: '#3b82f6',
          tension: 0.1
        },
        {
          label: '市场信心指数',
          data: sentimentData.value.confidenceTrend,
          borderColor: '#10b981',
          tension: 0.1
        },
        {
          label: '社交媒体情绪',
          data: sentimentData.value.socialMediaTrend,
          borderColor: '#8b5cf6',
          tension: 0.1
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: 'top'
        },
        tooltip: {
          mode: 'index',
          intersect: false
        }
      },
      scales: {
        y: {
          beginAtZero: true,
          max: 100
        }
      }
    }
  })
}

// 辅助函数
function getSentimentColor(value) {
  if (value >= 75) return 'text-green-600 dark:text-green-400'
  if (value >= 50) return 'text-yellow-600 dark:text-yellow-400'
  if (value >= 25) return 'text-orange-600 dark:text-orange-400'
  return 'text-red-600 dark:text-red-400'
}

function getSentimentLabel(value) {
  if (value >= 75) return '极度乐观'
  if (value >= 50) return '乐观'
  if (value >= 25) return '悲观'
  return '极度悲观'
}

function getConfidenceColor(value) {
  if (value >= 0.75) return 'text-green-600 dark:text-green-400'
  if (value >= 0.5) return 'text-yellow-600 dark:text-yellow-400'
  if (value >= 0.25) return 'text-orange-600 dark:text-orange-400'
  return 'text-red-600 dark:text-red-400'
}

function getConfidenceLabel(value) {
  if (value >= 0.75) return '高度信心'
  if (value >= 0.5) return '中等信心'
  if (value >= 0.25) return '低信心'
  return '极低信心'
}

function getTopicColor(sentiment) {
  if (sentiment > 0.5) return 'bg-green-200 dark:bg-green-700 text-green-800 dark:text-green-200'
  if (sentiment < -0.5) return 'bg-red-200 dark:bg-red-700 text-red-800 dark:text-red-200'
  return 'bg-gray-200 dark:bg-gray-600 text-gray-800 dark:text-gray-200'
}

function getNewsSentimentClass(sentiment) {
  if (sentiment > 0.5) return 'bg-green-200 dark:bg-green-700 text-green-800 dark:text-green-200'
  if (sentiment < -0.5) return 'bg-red-200 dark:bg-red-700 text-red-800 dark:text-red-200'
  return 'bg-yellow-200 dark:bg-yellow-700 text-yellow-800 dark:text-yellow-200'
}

function getNewsSentimentLabel(sentiment) {
  if (sentiment > 0.5) return '积极'
  if (sentiment < -0.5) return '消极'
  return '中性'
}

// 监听数据变化
watch(sentimentData, () => {
  if (sentimentData.value) {
    updateSentimentTrendChart()
  }
})
</script>